#include "main.h"
#include <algorithm>
#include <iostream>
#include <filesystem>
#include <fstream>
#include <sstream>
#include <windows.h> // 必须加这个！

using namespace std;
namespace fs = std::filesystem;

// 全局变量
const char* dbName = "data.db";
const char* LocationTableName = "Location";
std::vector<LocationStruct> LocationTable;
std::vector<LocationStruct> LocationTable_Spot;
std::vector<LocationStruct> LocationTable_Campus;

// 初始化函数
void init(void) {
    std::string dbFullPath = (fs::current_path() / "data.db").string();
    std::cout << "数据库路径：" << dbFullPath << std::endl;
    LocationTable = readLocations(dbFullPath);
}

int main() {
    // ⭐⭐ 重要：一启动，强制切换当前目录 ⭐⭐
    char exeFullPath[MAX_PATH];
    GetModuleFileNameA(NULL, exeFullPath, MAX_PATH);
    fs::path exeDir = fs::path(exeFullPath).parent_path();
    fs::current_path(exeDir);
    std::cout << "当前目录已切换到: " << fs::current_path() << std::endl;

    init();

    crow::SimpleApp app;

    // 注册API接口！一定要有！
    registerRoutes(app);

    // 首页重定向
    CROW_ROUTE(app, "/")([]() {
        crow::response res(302);
        res.set_header("Location", "/locations.html");
        return res;
        });

    // 托管 fronted 文件夹静态资源
    app.route_dynamic("/<path>")([](const crow::request& req, std::string path) {
        std::string frontedFolder = "./fronted/"; // ⭐ 注意这里，已经是当前目录下找 fronted
        std::string fullPath = frontedFolder + path;
        std::ifstream in(fullPath, std::ios::binary);
        if (!in) {
            return crow::response(404);
        }
        std::ostringstream contents;
        contents << in.rdbuf();
        return crow::response(contents.str());
        });

    app.port(8080).run();
}
